#include "ring_queue.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include "task.hpp"

void* consumer(void* args)
{
    qds::ring_queue<qds::task>* rq = (qds::ring_queue<qds::task>*)args;
    
    while(true)
    {
        qds::task t;
        rq->pop(&t);
        t();
        //sleep(1);
    }
}

void* producer(void* args)
{
    qds::ring_queue<qds::task>* rq = (qds::ring_queue<qds::task>*)args;
    const std::string opera = "+-*/%";

    while(true)
    {
        int x = rand() % 100 + 1;
        int y = rand() % 100 + 1;
        char op = opera[rand() % opera.size()];
        qds::task t(x, y, op);

        rq->push(t);
        std::cout << pthread_self() << "线程派发了一个任务:" << t << " = ?" << std::endl;
        sleep(1);
    }
}

int main()
{
    srand((long long)time(nullptr));

    qds::ring_queue<qds::task>* rq = new qds::ring_queue<qds::task>();

    pthread_t csm1, csm2, csm3, pdc1, pdc2;
    pthread_create(&csm1, nullptr, consumer, (void*)rq);
    pthread_create(&csm2, nullptr, consumer, (void*)rq);
    pthread_create(&csm3, nullptr, consumer, (void*)rq);
    pthread_create(&pdc1, nullptr, producer, (void*)rq);
    pthread_create(&pdc2, nullptr, producer, (void*)rq);

    pthread_join(csm1, nullptr);
    pthread_join(csm2, nullptr);
    pthread_join(csm3, nullptr);
    pthread_join(pdc1, nullptr);
    pthread_join(pdc2, nullptr);

    return 0;
}
